package com.joker.airoleplayplatformback.controller;

import com.joker.airoleplayplatformback.domain.entity.R;
import com.joker.airoleplayplatformback.service.VoiceChatService;
import com.joker.airoleplayplatformback.utils.WebSocketConnectionManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 语音处理控制器
 * @author feixiang.li
 * @since 2025-09-27
 */
@Slf4j
@RestController
@RequestMapping("/api/voice")
@Tag(name = "语音处理", description = "语音文件上传和处理接口")
public class VoiceController {

    @Autowired
    private VoiceChatService voiceChatService;

    @Autowired
    private WebSocketConnectionManager connectionManager;

    @PostMapping("/upload")
    @Operation(summary = "上传语音文件进行处理")
    public R<String> uploadVoiceFile(
            @RequestParam("audioFile") MultipartFile audioFile,
            @RequestParam("userId") String userId,
            @RequestParam("agentId") String agentId,
            @RequestParam("sessionId") String sessionId,
            @RequestParam(value = "websocketSessionId", required = false) String websocketSessionId) {
        
        try {
            log.info("接收到语音文件上传请求: userId={}, agentId={}, sessionId={}, fileSize={}", 
                    userId, agentId, sessionId, audioFile.getSize());

            if (audioFile.isEmpty()) {
                return R.error(400, "音频文件不能为空");
            }

            // 验证文件类型
            String originalFilename = audioFile.getOriginalFilename();
            if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".mp3") 
                    && !originalFilename.toLowerCase().endsWith(".wav")
                    && !originalFilename.toLowerCase().endsWith(".webm"))) {
                return R.error(400, "不支持的音频文件格式，仅支持 MP3、WAV、WebM 格式");
            }

            // 保存临时文件
            String tempFileName = "voice_" + UUID.randomUUID() + "_" + originalFilename;
            Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
            Path tempFilePath = tempDir.resolve(tempFileName);
            
            try {
                Files.copy(audioFile.getInputStream(), tempFilePath);
                log.info("音频文件保存到临时目录: {}", tempFilePath);

                // 如果有WebSocket会话ID，通过WebSocket处理
                if (websocketSessionId != null && !websocketSessionId.isEmpty()) {
                    // 通过现有的语音处理流程
                    voiceChatService.processVoiceFile(websocketSessionId, tempFilePath.toString());
                    return R.ok("语音文件处理中，结果将通过WebSocket返回");
                } else {
                    // 直接处理并返回结果
                    // 这里可以添加同步处理逻辑
                    return R.ok("语音文件上传成功: " + tempFilePath.toString());
                }

            } catch (IOException e) {
                log.error("保存音频文件失败", e);
                return R.error(500, "保存音频文件失败: " + e.getMessage());
            }

        } catch (Exception e) {
            log.error("处理语音文件上传失败", e);
            return R.error(500, "处理语音文件失败: " + e.getMessage());
        }
    }

    @PostMapping("/process-mp3")
    @Operation(summary = "处理MP3语音文件")
    public R<byte[]> processMp3File(
            @RequestParam("audioFile") MultipartFile audioFile,
            @RequestParam("userId") String userId,
            @RequestParam("agentId") String agentId,
            @RequestParam("sessionId") String sessionId) {
        
        try {
            log.info("处理MP3文件: userId={}, agentId={}, sessionId={}, fileSize={}", 
                    userId, agentId, sessionId, audioFile.getSize());

            if (audioFile.isEmpty()) {
                return R.error(400, "音频文件不能为空");
            }

            // 验证是否为MP3文件
            String originalFilename = audioFile.getOriginalFilename();
            if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".mp3")) {
                return R.error(400, "仅支持MP3格式的音频文件");
            }

            // 保存临时文件
            String tempFileName = "mp3_" + UUID.randomUUID() + ".mp3";
            Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
            Path tempFilePath = tempDir.resolve(tempFileName);
            
            Files.copy(audioFile.getInputStream(), tempFilePath);
            log.info("MP3文件保存成功: {}", tempFilePath);

            // 处理MP3文件并返回处理后的音频数据
            byte[] processedAudio = voiceChatService.processMp3File(tempFilePath.toString(), userId, agentId, sessionId);
            
            // 清理临时文件
            Files.deleteIfExists(tempFilePath);
            
            return R.ok(processedAudio);

        } catch (Exception e) {
            log.error("处理MP3文件失败", e);
            return R.error(500, "处理MP3文件失败: " + e.getMessage());
        }
    }

    @GetMapping("/download/{filename}")
    @Operation(summary = "下载语音文件")
    public R<byte[]> downloadVoiceFile(@PathVariable String filename) {
        try {
            // 这里可以添加从OSS下载文件的逻辑
            // 暂时返回空实现
            return R.error(501, "下载功能暂未实现");
        } catch (Exception e) {
            log.error("下载语音文件失败", e);
            return R.error(500, "下载语音文件失败: " + e.getMessage());
        }
    }
}
